<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use DB;
use Exception;

class SystemMessagePublishedNotify implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public $tries = 5;
	public $maxExceptions = 3;
    protected $messageData = [];
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($messageData)
    {
        $this->messageData = $messageData;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $channelType = $this->messageData['channelType'] ?? 'default';
        switch ($channelType) {
            case 'feedback':
            case 'collections':
            case 'dirty':
            case 'cream':
            case 'followers':
            case 'report':
            case 'votes':
            case 'adopts':
            case 'favourites':
            case 'forks':
            case 'messages':
                broadcast(new \App\Events\ReportNews(
                    $this->messageData['message'],
                    $this->messageData['title'] ?? null,
                    $this->messageData['message_type']  ?? null,
                    $this->messageData['position'] ?? null,
                    $this->messageData['duration'] ?? null,
                    $channelType,
                    $this->messageData['data'] ?? null
                ));
                break;
            default:
                broadcast(new \App\Events\SystemNews(
                    $this->messageData['message'],
                    $this->messageData['title'] == '' ? null : $this->messageData['title'],
                    $this->messageData['message_type'] == '' ? null : $this->messageData['message_type'],
                    $this->messageData['position'] == '' ? null : $this->messageData['position'],
                    $this->messageData['duration'] == '' ? null : (int)$this->messageData['duration'],
                    $channelType,
                    empty($this->messageData['data']) ? null : $this->messageData['data']
                ))->toOthers();
                break;
        }
    }

	/**
	 * 任务未能处理
	 *
	 * @param  Exception  $exception
	 * @return void
	 */
	public function failed(Exception $exception)
	{
	    DB::table('job_failed_detail_records')->insert([
	        'tags' => '系统消息推送',
	        'content' => json_encode($this->messageData, 256),
	        'exception' => $exception->getMessage()
	    ]);
	}
}
